<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Java 内存模型——底层原理 | 王开琦的个人小站</title><meta name="author" content="王开琦"><meta name="copyright" content="王开琦"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="从Java 代码到CPU指令*.java  源程序文件编译成 * class( bytecode，字节码)，*.class文件就与平台无关了。平台指的是各个操作系统。   最开始，我们编写的时 Java 代码，是 *.java文件； 在编译 （javac 命令）后，从刚才的 *.java 文件会产生一个新的 Java 字节码文件 (*.class）； JVM 会执行刚才生成的字节码文件 （*.cl">
<meta property="og:type" content="article">
<meta property="og:title" content="Java 内存模型——底层原理">
<meta property="og:url" content="https://blog.wkq.pub/blog/1-Java-%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="王开琦的个人小站">
<meta property="og:description" content="从Java 代码到CPU指令*.java  源程序文件编译成 * class( bytecode，字节码)，*.class文件就与平台无关了。平台指的是各个操作系统。   最开始，我们编写的时 Java 代码，是 *.java文件； 在编译 （javac 命令）后，从刚才的 *.java 文件会产生一个新的 Java 字节码文件 (*.class）； JVM 会执行刚才生成的字节码文件 （*.cl">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog.wkq.pub/cover/Java.png">
<meta property="article:published_time" content="2021-12-02T13:34:16.000Z">
<meta property="article:modified_time" content="2022-04-21T15:50:59.463Z">
<meta property="article:author" content="王开琦">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog.wkq.pub/cover/Java.png"><link rel="shortcut icon" href="/media/favicon.ico"><link rel="canonical" href="https://blog.wkq.pub/blog/1-Java-%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java 内存模型——底层原理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-04-21 23:50:59'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/cover/Java.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">王开琦的个人小站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java 内存模型——底层原理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-02T13:34:16.000Z" title="发表于 2021-12-02 21:34:16">2021-12-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-04-21T15:50:59.463Z" title="更新于 2022-04-21 23:50:59">2022-04-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/Java-%E5%B9%B6%E5%8F%91/">Java 并发</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="从Java-代码到CPU指令"><a href="#从Java-代码到CPU指令" class="headerlink" title="从Java 代码到CPU指令"></a>从Java 代码到CPU指令</h2><p><code>*.java</code>  源程序文件编译成 <code>* class</code>( bytecode，字节码)，<code>*.class</code>文件就与平台无关了。平台指的是各个操作系统。</p>
<p><img src= "" data-lazy-src="从Java代码到CPU指令.png" alt=""></p>
<ol>
<li>最开始，我们编写的时 Java 代码，是 <code>*.java</code>文件；</li>
<li>在编译 （javac 命令）后，从刚才的 <code>*.java</code> 文件会产生一个新的 Java 字节码文件 (<code>*.class</code>）；</li>
<li>JVM 会执行刚才生成的字节码文件 （<code>*.class</code>）,并把字节码文件<font style='color=red'>转化</font>为机器指令；</li>
<li>机器指令可以直接在CPU上执行，也就是最终的程序执行；</li>
</ol>
<div class="note info simple"><p>JVM 实现会带来不同的 “<font style='color=red'>翻译</font>”，不同平台的CPU机器指令又千差万别，无法保证并发安全的效果一致。</p>
<p>最开始没有Java 内存模型的时候，不同平台的<font style='color=red'>翻译</font>”效果确实是不一样，所以存在同一段代码不同的运行平台运行效果不一样。也就没法保证并发安全效果的一致。</p>
<p>后来产生了JMM，提供转化过程的<font style='color=red'>规范</font>、<font style='color=red'>原则</font></p>
</div>
<h2 id="JMM"><a href="#JMM" class="headerlink" title="JMM"></a>JMM</h2><div class="hide-block"><button type="button" class="hide-button button--animated" style="">JVM内存结构 VS Java内存模型 VS Java 对象模型
    </button><div class="hide-content"><ul>
<li><p>JVM 内存结构，和Java 虚拟机的运行时区域有关。</p>
</li>
<li><p>Java 内存模型，和Java的并发编程有关。</p>
</li>
<li><p>Java 对象模型，和Java 对象在虚拟机中的表现形式有关。</p>
<p><img src= "" data-lazy-src="Java对象模型.png" alt=""></p>
<ul>
<li>Java对象自身的存储模型</li>
<li>JVM会给这个类创建一个instanceClass ，保存在方法区，用来在JVM层表示该Java 类</li>
<li>当我们在Java代码中，使用new创建一个对象的时候，JVM会创建一个instanceOopDesc对象，这个对象中包含了对象头以及实例数据</li>
</ul>
</li>
</ul>
</div></div>
<p>Java Memory Model ，Java 内存模型，简称 JMM</p>
<div class="note primary simple"><p>为什么需要JMM</p>
</div>
<ul>
<li>C语言不存在内存模型的概念</li>
<li>运行结果依赖处理器，不同处理器结果不一样</li>
<li>无法保证并发安全</li>
<li>需要一个标准，让多线程运行结果的结果可预期 ，避免出现不同处理器运行结果不一致的情况</li>
</ul>
<div class="note primary simple"><p>JMM是规范 </p>
</div>
<ul>
<li>是一组<strong>规范</strong>，需要各个JVM的实现来遵守JMM规范（还需要编译器，CPU进行配合），以便于开发者可以<strong>利用这些规范，更方便的开发多线程程序</strong>。</li>
<li>如果没有这样的一个Java 内存模型来规范，那么很可能经过了不同的JVM的不同规则的重排序之后，<strong>导致不同虚拟机上运行的结果不一样</strong>。</li>
</ul>
<div class="note primary simple"><p>JMM是工具类和关键字的原理</p>
</div>
<ul>
<li>volatile、synchronized、Lock等的<strong>原理都是JMM</strong>。</li>
<li>如果<strong>没有JMM</strong>，那就需要我们自己指定什么时候用内存栅栏等，有了JMM，使得开发者只需要用<strong>同步工具和关键字</strong>就可以开发并发程序。</li>
</ul>
<div class="note info simple"><p>JMM最重要的3点内容： <strong>重排序</strong>、<strong>（内存）可见性</strong>、<strong>原子性</strong>，JMM最最主要的内容都在这三点中体现出来了。</p>
</div>
<h2 id="重排序"><a href="#重排序" class="headerlink" title="重排序"></a>重排序</h2><h3 id="重排序的例子"><a href="#重排序的例子" class="headerlink" title="重排序的例子"></a>重排序的例子</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 描述： 演示重排序的现象</span></span><br><span class="line"><span class="comment"> * ”直到达到某个条件才停止“，测试小概率事件。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OutOfOrderExecution</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> x = <span class="number">0</span>, y = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> a = <span class="number">0</span>, b = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (; ; ) &#123;</span><br><span class="line">            i++;</span><br><span class="line">            x = <span class="number">0</span>;</span><br><span class="line">            y = <span class="number">0</span>;</span><br><span class="line">            a = <span class="number">0</span>;</span><br><span class="line">            b = <span class="number">0</span>;</span><br><span class="line">            CountDownLatch latch = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span><span class="comment">/*需要倒计时的次数*/</span>);</span><br><span class="line">            Thread threadOne = <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    <span class="comment">//在需要等待的地方加上栅栏</span></span><br><span class="line">                    a = <span class="number">1</span>;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        latch.await();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                    x = b;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            Thread threadTwo = <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    <span class="comment">//在需要等待的地方加上栅栏</span></span><br><span class="line">                    b = <span class="number">1</span>;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        latch.await();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                    y = a;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            threadTwo.start();</span><br><span class="line">            threadOne.start();</span><br><span class="line">            <span class="comment">//倒数一次放开闸门，因为构造函数中设置了1</span></span><br><span class="line">            latch.countDown();</span><br><span class="line">            threadOne.join();</span><br><span class="line">            threadTwo.join();</span><br><span class="line">            String result = <span class="string">&quot;第&quot;</span> + i + <span class="string">&quot;次（&quot;</span> + x + <span class="string">&quot;,&quot;</span> + y + <span class="string">&quot;)&quot;</span>;</span><br><span class="line">            <span class="keyword">if</span> (x == <span class="number">1</span> &amp;&amp; y == <span class="number">1</span>) &#123;</span><br><span class="line">                System.out.println(result);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(result);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>这四行赋值代码的执行顺序决定了最终x和y的结果，一共有3种情况：</p>
<ol>
<li>a=1；x=b(0)；b=1；y=a(1)，最终结果是 x=0，y=1</li>
<li>b=1；y=a(0)；a=1；x=b(1)，最终结果是 x=1，y=0</li>
<li>b=1；a=1；x=b(1)；y=a(1)，最终结果是 x=1，y=1 </li>
</ol>
<div class="note primary simple"><p>重排序分析</p>
</div>
<p>虽然代码执行顺序可能有多种情况，但是在线程1内部，也就是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a=<span class="number">1</span>;</span><br><span class="line">x=b;</span><br></pre></td></tr></table></figure>
<p><strong>这两行代码的执行顺序，是不会改变的</strong>，也就是 a= 1 会在x=b 前执行；同理，线程2 的 b=1会在y=a前执行。</p>
<p>但线程1和线程2 ，它们的执行顺序是可以交替的，对于一个线程内部的代码而言是不交替的。以这种思路进行分析，只会分析出以上的三种执行结果。无论怎么运行，都不会出现 x=0，y=0的情况</p>
</article><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="/cover/Java.png" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">王开琦</div><div class="author-info__description">今日事今日毕</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%8EJava-%E4%BB%A3%E7%A0%81%E5%88%B0CPU%E6%8C%87%E4%BB%A4"><span class="toc-number">1.</span> <span class="toc-text">从Java 代码到CPU指令</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JMM"><span class="toc-number">2.</span> <span class="toc-text">JMM</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%87%8D%E6%8E%92%E5%BA%8F"><span class="toc-number">3.</span> <span class="toc-text">重排序</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%87%8D%E6%8E%92%E5%BA%8F%E7%9A%84%E4%BE%8B%E5%AD%90"><span class="toc-number">3.1.</span> <span class="toc-text">重排序的例子</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="3.数据库-数据库监控与调优-特定语句的原理和调优"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优">3.数据库-数据库监控与调优-特定语句的原理和调优</a><time datetime="2022-04-22T08:14:26.000Z" title="发表于 2022-04-22 16:14:26">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="数据库调优理论"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论">数据库调优理论</a><time datetime="2022-04-22T08:13:31.000Z" title="发表于 2022-04-22 16:13:31">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="慢查询发现与分析"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析">慢查询发现与分析</a><time datetime="2022-04-22T08:12:32.000Z" title="发表于 2022-04-22 16:12:32">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM 调优理论"/></a><div class="content"><a class="title" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论">JVM 调优理论</a><time datetime="2022-04-21T06:40:41.000Z" title="发表于 2022-04-21 14:40:41">2022-04-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="服务治理Eureka"/></a><div class="content"><a class="title" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka">服务治理Eureka</a><time datetime="2022-04-13T13:18:27.000Z" title="发表于 2022-04-13 21:18:27">2022-04-13</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="footer_custom_text">Copyright© 2022 blog.wkq.pub <span>陇ICP备2021003596号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      true && mermaid.init()
    })
  }
}</script></div><div class="aplayer no-destroy" data-id="7675104902" data-server="tencent" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script></div><script src="/live2d_models/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2d_models/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2d_models/assets/penchan.model.json"},"display":{"position":"left","width":100,"height":150,"hOffset":-10,"vOffset":40},"mobile":{"show":true},"react":{"opacity":0.7},"log":false});</script></body></html>